package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.dao.AddressMapper;
import org.linlinjava.litemall.db.models.Address;
import org.linlinjava.litemall.db.service.AddressService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements AddressService {

    @Override
    public List<Address> queryByUid(Long uid) {
        QueryWrapper<Address> query = new QueryWrapper<>();
        query.eq("user_id", uid);
        return baseMapper.selectList(query);
    }

    @Override
    public Address query(Long userId, Long id) {
        QueryWrapper<Address> query = new QueryWrapper<>();
        query.eq("user_id", userId).eq("id", id);
        return baseMapper.selectOne(query);
    }

    @Override
    public Address findDefault(Long userId) {
        QueryWrapper<Address> query = new QueryWrapper<>();
        query.eq("user_id", userId).eq("is_default", true);
        return baseMapper.selectOne(query);
    }

    @Override
    public void resetDefault(Long userId) {
        UpdateWrapper<Address> update = new UpdateWrapper<>();
        update.set("is_default", false);
        update.eq("user_id", userId);
        baseMapper.update(new Address(), update);
    }

    @Override
    public IPage<Address> querySelective(Long userId, String name, Integer pageNo, Integer pageSize) {
        Page<Address> page = new Page<>();
        QueryWrapper<Address> query = new QueryWrapper<>();
        query.eq(userId!=null, "user_id", userId);
        query.like(!StringUtils.isEmpty(name), "name", name);
        return baseMapper.selectPage(page, query);
    }
}
